import { defineComponent, nextTick, onMounted, ref, type PropType } from 'vue'
import type { JsonSchema, Slots } from '../types'
import icons from '../assets'
import { formState } from '../mixins/useState'
import { getProp } from '@/components/cms/utils'

export default defineComponent({
  inheritAttrs: true,
  emits: ['valueChange'],
  props: {
    schema: {
      type: Object as PropType<JsonSchema>,
      default: () => ({})
    },
    slots: {
      type: Object as PropType<Slots>,
      default: () => undefined
    }
  },
  setup(props, ctx) {
    const inputValue = ref('left')
    const list = ['left', 'center', 'right', 'between']
    const handleChange = () => {
      if (!props.schema.field) {
        console.warn('字段没有传递')
        return
      }
      const value = {
        path: props.schema.field,
        value: inputValue.value
      }
      ctx.emit('valueChange', value)
    }

    onMounted(() => {
      nextTick(() => {
        const value = getProp(formState.model, props.schema.field as string).value as string
        inputValue.value = value
      })
    })
    return () => {
      return (
        <a-radio-group
          onChange={() => handleChange()}
          class="text-icon-position"
          v-model={[inputValue.value, 'value']}
          button-style="solid"
        >
          {list.map((item) => (
            <a-radio-button value={item}>
              <img src={icons[item]} />
            </a-radio-button>
          ))}
        </a-radio-group>
      )
    }
  }
})
